<template>
  <div class="login">
    <div class="login-logo">
      <!-- 鸿博志成logo -->
      <img src="../../assets/images/login/logo.jpg" />
    </div>
    <!--如果有轮播的话: 轮播位置-->
    <div class="login-banner">
      <img v-if="systemCode == 'business'" src="./assets/img/banner2.png" alt="" />
      <img v-else src="./assets/img/banner.png" alt="" />
    </div>
    <div class="login-form" id="login-form">
      <div class="login-form-title">{{ systemCode == 'business' ? '智厨业务管理系统' : '伙食保障精细管理系统' }}</div>
      <div class="login-form-line"></div>
      <div class="login-form-section" :style="select.account ? 'border-bottom: 0.0133333333rem solid black' : ''
        ">
        <div class="section-icon">
          <img src="../../assets/images/login/8.svg" v-if="select.account" />
          <img src="../../assets/images/login/8-1.svg" v-else />
        </div>
        <div class="section-input">
          <input type="text" @focus="select.account = true" v-model="form.account" @keydown.enter="onSubmit"
            @blur="select.account = false" />
        </div>
      </div>
      <div class="login-form-section" :style="select.password ? 'border-bottom: 0.0133333333rem solid black' : ''
        ">
        <div class="section-icon">
          <img src="../../assets/images/login/9.svg" v-if="select.password" />
          <img src="../../assets/images/login/9-1.svg" v-else />
        </div>

        <div class="section-input">
          <input :type="select.eyes ? 'text' : 'password'" v-model="form.password" @keydown.enter="onSubmit"
            @focus="select.password = true" @blur="select.password = false" />
        </div>
        <div class="section-right" @click="select.eyes = !select.eyes">
          <img src="../../assets/images/login/10.svg" v-if="select.eyes" />
          <img src="../../assets/images/login/10-1.svg" v-else />
        </div>
      </div>
      <div class="login-form-submit" @click="onSubmit">
        <div class="submit-label">登录</div>
        <div class="submit-filter"></div>
      </div>
      <div class="version-wrap">版本:{{ versionNo }}</div>
      <!-- <div class="login-form-qrcode">
        <img src="../../assets/images/login/qrcode.png" alt="" />
      </div> -->
      <!--<div class="login-form-setter" @click="onSetter">
        <u-icon name="setting" size="18" color="#1990FF"></u-icon>
      </div>-->
    </div>
  </div>
</template>

<script>
import { firstRouter, baseRouters, errRouters, } from "@/router/routers";
import {
  login,
  getPermissionForRoleId,
  postPermissionForRoleId,
  getUserBaseInfo,
  getVersionNo
} from "@/api/organ/system";

export default {
  data() {
    return {
      systemCode: localStorage.getItem('systemCode'),
      isLogin: false,
      select: {
        account: false,
        password: false,
        eyes: false,
      },
      versionNo: '',
      form: {
        account: "",
        password: "",
      },
    };
  },
  mounted() {
	// 判断系统
	const currentUrl = window.location.port;
        if (!window.localStorage.getItem("systemCode")) {
          let systemCode = currentUrl == 4200 ? "business" : "organ";
          window.localStorage.setItem("systemCode", systemCode);
        }
    this.removeElement([1, 2, 5], 11)
    this.setRemUnit();
    this.getVersionNoApi()
    if (window.location.href.indexOf("/login") > -1) {
      //防止页面后退
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", function (event) {
        history.pushState(null, null, document.URL);
      });
    }
  },
  methods: {
    removeElement(nums, val) {
      if (val < 0) {
        return 0
      }
      if (nums.length < 1) return -1
      for (let i = 0; i < nums.length; i++) {

      }
    },

    onCancel() {
      this.isLogin = false;
      this.$cu.hideLoading(1.5);
    },
    setRemUnit() {
      var docEl = document.documentElement;
      var rem = docEl.clientWidth / 10;
      let fontSize = docEl.style.fontSize.split("px")[0];
      let abs =
        document.body.clientHeight -
        document.getElementById("login-form").offsetHeight;
      if (document.getElementById("login-form")) {
        if (rem > (fontSize ? fontSize : 0) && abs < 100) {
          docEl.style.fontSize = (abs < 0 ? 180 : rem) - Math.abs(abs) + "px";
          return;
        }
      }
      docEl.style.fontSize = (rem > 180 ? 180 : rem) + "px";
    },
    // 获取版本信息
    getVersionNoApi() {
      return new Promise((resolve) => {
        getVersionNo({
        }).then((res) => {
          if (res.code == 1) {
            this.versionNo = res.data.versionNo
          } else {
            this.$Message.error(res.retMsg)
          }
          resolve()
        });
      });
    },
    readNodes(nodes = [], arr = []) {

      for (let item of nodes) {
        arr.push(item);
        item.title = item.name;
        item.path = item.url;
        item.meta = {
          icon: item.icon,
          title: item.title,
        };
        item.selected = false;
        if (item.children && item.children.length) {
          item.component = () =>
            import("@/components/parent-view/parent-view.vue");
        } else {
          item.component = () => import(`@/${item.filePath}`);
        }
        if (item.children && item.children.length)
          this.readNodes(item.children, arr);
      }
      return arr;

    },

    // 获取用户基础信息
    getUserBaseInfoApi({ token }) {
      return new Promise((resolve) => {
        getUserBaseInfo({ token })
          .then((res) => {
            if (res.code === 1) {
              console.log("===========", res.data);
              res.data.token = token;
              this.$store.commit("$uStore", {
                name: "vuex_user",
                value: res.data,
              });
              // this.$router.push("/home");
              resolve();
            } else this.onCancel();
          })
          .catch(() => (this.isLogin = false));
      });
    },
    // 角色id换权限
    getPermissionForRoleIdApi() {
      return new Promise((resolve) => {
        console.log(this.vuex_user.role);
        let roles = this.$cu.deepClone(this.vuex_user.role);
        roles = roles.map((v) => {
          v = v.id;
          return v;
        });
        postPermissionForRoleId(
          {
            roles: roles,
            returnSystem: false,
            systemCode: window.localStorage.getItem("systemCode")
          }

        )
          .then((res) => {
            if (res.code === 1) {
              this.$cu.hideLoading();
              this.$Message.success("登录成功");
              let router = res.data;
              console.log(res);
              this.readNodes(router);
              firstRouter[0].children = router;
              this.$store.commit("$uStore", {
                name: "vuex_routers",
                value: firstRouter,
              });
              firstRouter.forEach((val) => {
                this.$router.addRoute(val);
              });
              baseRouters.forEach((val) => {
                this.$router.addRoute(val);
              });
              errRouters.forEach((val) => {
                this.$router.addRoute(val);
              });
              this.$store.dispatch('getAreaListApi')
              this.$router.push({
                name: 'home',
                params: {
                  refreshFlag: true
                }
              });
              resolve();
            } else this.onCancel();
          })
          .catch(() => (this.isLogin = false));
      });
    },
    onSubmit() {
      if (this.isLogin) return this.$Message.info("别着急,喝杯茶冷静下..");
      if (!this.form.account) {
        return this.$Message.error("账号不能为空");
      } else if (!this.form.password) {
        return this.$Message.error("密码不能为空");
      } else {
        this.isLogin = true;
        this.$cu.showLoading({ content: "角色登录中.." });
        login({ loginName: this.form.account, password: this.form.password })
          .then((res) => {
            if (res.code === 1) {
              this.$store.commit("$uStore", {
                name: "kitchenMode",
                value: res.data.kitchenMode,
              });

              this.$store.commit("$uStore", {
                name: "vuex_user",
                value: res.data,
              });
              this.getUserBaseInfoApi(res.data).then(() => {
                this.getPermissionForRoleIdApi()
              })
            } else this.onCancel();
          })
          .catch(() => (this.isLogin = false));
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "login";
</style>
